package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.exception.BusinessException;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.util.SMSUtils;
import com.itheima.reggie.util.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private HttpSession session;
    @RequestMapping("/login")
    public R<String> login(@RequestBody User user){
        User loginUser = userService.login(user);

        if (loginUser==null){
            user.setStatus(1);
            userService.add(user);
            session.setAttribute("user", user.getId());
            session.removeAttribute("code");
            return R.success("登录成功");
        }

        session.setAttribute("user", loginUser.getId());
        session.removeAttribute("code");
        return R.success("登录成功");
    }

    @RequestMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user){
        //1.生成一个4位随机数字验证码
        String code = ValidateCodeUtils.generateValidateCode4String(4);
        //打印验证码
        System.out.println("验证码："+code);

        /*//2.发送短信
        SMSUtils.sendMessage("黑马旅游网","SMS_198917972",user.getPhone(),code);
        session.setAttribute("code", code);*/
        session.setAttribute("code", code);

        return R.success("成功");
    }

    @RequestMapping("/loginout")
    public R<String> loginOut(){
        session.invalidate();
        return R.success("退出成功");
    }

    /*@RequestMapping("/login")
    public R<String> login(@RequestBody Map<String,String> user){
        String phone = user.get("phone");
        String code = user.get("code");//网页端传来的验证码数据
        String code1 = (String) session.getAttribute("code");
        if (!(code.equals(code1))){
            throw new BusinessException("验证码错误");
        }

        User user1 = new User();
        user1.setPhone(phone);

        User login = userService.login(user1);

        if (login!=null){
            session.setAttribute("user", login.getId());
            return R.success("登录成功");
        }else{
            //如果数据不存在,创建一个新用户用于注册
            user1.setStatus(1);
            userService.add(user1);
            session.setAttribute("user", login.getId());
            return R.success("注册登录");
        }


    }*/

}
